package com.worldcup.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.worldcup.common.CommonResult;
import com.worldcup.model.PredictGroup;
import com.worldcup.model.PredictKnockout;
import com.worldcup.model.dto.*;
import com.worldcup.service.PhantomJsService;
import com.worldcup.service.PredictGroupService;
import com.worldcup.service.PredictKnockoutService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author duwan.zq
 * @date 2018/05/26
 */
@RestController
@RequestMapping("/api/java/predict")
public class PredictController {

    private final static Logger logger = LoggerFactory.getLogger(PredictController.class);

    @Autowired
    private PredictGroupService predictGroupService;

    @Autowired
    private PredictKnockoutService predictKnockoutService;

    @Autowired
    private PhantomJsService phantomJsService;

    @RequestMapping(path = "/predictAll", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public CommonResult predictAll(@Validated @RequestBody PredictAllDTO predictAllDTO){
        String openid = predictAllDTO.getOpenid();

        if(CollectionUtils.isNotEmpty(predictGroupService.getPredictGroup(openid))){
            predictGroupService.delete(openid);
        }

        if(CollectionUtils.isNotEmpty(predictKnockoutService.getPredictKnockout(openid))){
            predictKnockoutService.delete(openid);
        }

        //小组赛
        List<PredictTypeGroupDTO> groups = predictAllDTO.getGroups();
        if(CollectionUtils.isNotEmpty(groups)){
            List<PredictGroup> groupToInsert = new ArrayList<>();
            groups.forEach(predictTypeGroupDTO -> {
                if(CollectionUtils.isEmpty(predictTypeGroupDTO.getMatches())){
                    return;
                }
                predictTypeGroupDTO.getMatches().forEach(predictGroupDTO -> {
                    PredictGroup predictGroup = predictGroupDTO.toPredictGroup(openid, predictTypeGroupDTO.getGroup());
                    groupToInsert.add(predictGroup);
                });
            });
            predictGroupService.batchInsert(groupToInsert);
        }

        //淘汰赛
        List<PredictTypeKnockoutDTO> knockouts = predictAllDTO.getKnockouts();
        if(CollectionUtils.isNotEmpty(knockouts)){
            List<PredictKnockout> knockoutToInsert = new ArrayList<>();
            knockouts.forEach(predictTypeKnockoutDTO -> {
                if(CollectionUtils.isEmpty(predictTypeKnockoutDTO.getMatches())){
                    return;
                }
                predictTypeKnockoutDTO.getMatches().forEach(predictKnockoutDTO -> {
                    PredictKnockout predictKnockout = predictKnockoutDTO.toPredictKnockout(openid, predictTypeKnockoutDTO.getMatchType());
                    knockoutToInsert.add(predictKnockout);
                });
            });
            predictKnockoutService.batchInsert(knockoutToInsert);
        }

        return CommonResult.buildSuccess();
    }

    @RequestMapping(path = "/getAllPredict")
    public CommonResult getAllPredict(String openid){
        Assert.state(StringUtils.isNotBlank(openid), "openid is null");
        List<PredictGroup> predictGroups = predictGroupService.getPredictGroup(openid);
        List<PredictKnockout> predictKnockouts = predictKnockoutService.getPredictKnockout(openid);
        PredictAllDTO result = new PredictAllDTO(openid, predictGroups, predictKnockouts);
        return CommonResult.buildSuccess(result);
    }

    @RequestMapping(path="/getResultImage", method = RequestMethod.POST)
    public CommonResult getResultImage(@RequestBody String json) throws IOException, InterruptedException {
        JSONObject jsonObject = JSON.parseObject(json);
        String imageUrl = phantomJsService.createImage((String)jsonObject.get("html"));
        return CommonResult.buildSuccess(imageUrl);
    }
}
